import os
from random import random
import time
import uvicorn
from fastapi import FastAPI, File, UploadFile, Header
from starlette.responses import FileResponse
from typing import Optional

from Temperature import getTemp   # 温度接口
from Acceleration import getAccel # 加速度接口
from ultrasound import Ultrasound
echo = 9
trig = 10
us = Ultrasound(trig, echo)       # 超声波接口


app = FastAPI()

errno = 0
# get post put delete ..

@app.get("/")
async def root():
    return {"mgs":"Hello World!"}

@app.get("/temp")
async def temp():
    global errno
    try:
        temp = getTemp()
    except:
        errno = -1
    return {"error": errno,
            "temp": temp}


# 加速度
@app.get("/accel")
async def temp():
    global errno
    try:
        accel = getAccel()
    except:
        errno = -1
    return {"error": errno,
            "accel": accel}
# 超声波
@app.get("/distance")
async def temp():
    global errno
    try:
        dis = us.get_distance()
    except:
        errno = -1
    return {"error": errno,
            "distance": dis}
    
# 相机
@app.get("/cam")
async def camera():
    # global errno
    # png = open('avi.png', mode="rb")
    try:
        # 拍照的代码
        pass                # 路径                 # 类型
        return FileResponse('avi.png', media_type="image/png")
    except:
        errno = -1
        return {"errno": errno}

# 控制
@app.post("/controll")
async def controll(action: str):
    print("spin")
    # 控制的代码 action控制的参数
    return {"action": action}    
    


if __name__ == "__main__":
    uvicorn.run("main:app",
        host="0.0.0.0", port=2233, reload=True)
        # ssl_keyfile="keys/xmu-maker.cn.key",
        # ssl_certfile="keys/xmu-maker.cn.pem")
